package com.wchat.network.message;

import com.wchat.network.Configs;
import com.wchat.network.device.BroadCastTarget;

public class BroadCastSender extends Thread {

	private volatile boolean close = false;

	private WhoAmIMessage message;

	public BroadCastSender(WhoAmIMessage message) {
		super();
		setName("broadcaster");
		this.message = message;
	}

	@Override
	public void run() {
		while (!close && !isInterrupted()) {
			try {
				BroadCastTarget.getInstance().sendMessage(message);
			} catch (Exception e) {
				Configs.log("send broadcast message error", e);
			}
			synchronized (this) {
				try {
					wait(Configs.BROADCAST_WHOAMI_INTERVAL);
				} catch (InterruptedException e) {
					break;
				}
			}
		}
	}

	public void broadcastNow() {
		try {
			BroadCastTarget.getInstance().sendMessage(message);
			Configs.i("broadcast", "trigger a broadcast.");
		} catch (Exception e) {
			Configs.log("send broadcast message error", e);
		}
	}
	
	public void close() {
		close = true;
		synchronized (this) {
			notify();
		}
	}

}
